from django.db import models
from django.utils import timezone

class WechatUser(models.Model):
    """微信用户模型"""
    openid = models.CharField(max_length=100, unique=True, verbose_name='微信openid')
    nickname = models.CharField(max_length=100, default='微信用户', verbose_name='昵称')
    avatar = models.URLField(default='https://thirdwx.qlogo.cn/mmopen/vi_32/POgEwh4mIHO4nibH0KlMECNjjGxQUq24ZEaGT4poC6icRiccVGKSyXwibcPq4BWmiaIGuG1icwxaQX6grC9VemZoJ8rg/132', verbose_name='头像')
    gender = models.IntegerField(default=0, verbose_name='性别')  # 0-未知，1-男，2-女
    country = models.CharField(max_length=100, blank=True, null=True, verbose_name='国家')
    province = models.CharField(max_length=100, blank=True, null=True, verbose_name='省份')
    city = models.CharField(max_length=100, blank=True, null=True, verbose_name='城市')
    token = models.CharField(max_length=100, blank=True, null=True, verbose_name='登录token')
    token_expires_at = models.DateTimeField(blank=True, null=True, verbose_name='token过期时间')
    created_at = models.DateTimeField(auto_now_add=True, verbose_name='创建时间')
    updated_at = models.DateTimeField(auto_now=True, verbose_name='更新时间')

    class Meta:
        db_table = 'wechat_user'
        verbose_name = '微信用户'
        verbose_name_plural = verbose_name

    def is_token_valid(self):
        """检查token是否有效"""
        return timezone.now() <= self.token_expires_at

    def to_dict(self):
        """
        将对象转换为字典
        """
        return {
            'id': self.id,
            'openid': self.openid,
            'nickname': self.nickname,
            'avatar': self.avatar,
            'gender': self.gender,
            'country': self.country,
            'province': self.province,
            'city': self.city,
            'token': self.token,
            'token_expires_at': self.token_expires_at.strftime('%Y-%m-%d %H:%M:%S') if self.token_expires_at else None,
            'created_at': self.created_at.strftime('%Y-%m-%d %H:%M:%S'),
            'updated_at': self.updated_at.strftime('%Y-%m-%d %H:%M:%S')
        } 